package com.atguigu.lease.web.admin.controller.lease;


import com.atguigu.lease.common.result.Result;
import com.atguigu.lease.model.entity.UserCredit;
import com.atguigu.lease.model.entity.ViewAppointment;
import com.atguigu.lease.model.enums.AppointmentStatus;
import com.atguigu.lease.web.admin.service.UserCreditService;
import com.atguigu.lease.web.admin.service.UserInfoService;
import com.atguigu.lease.web.admin.service.ViewAppointmentService;
import com.atguigu.lease.web.admin.vo.appointment.AppointmentQueryVo;
import com.atguigu.lease.web.admin.vo.appointment.AppointmentVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxl.job.core.handler.annotation.XxlJob;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;


@Tag(name = "预约看房管理")
@RequestMapping("/admin/appointment")
@RestController
public class ViewAppointmentController {

    @Autowired
    private UserCreditService userCreditService;
    @Autowired
    private ViewAppointmentService viewAppointmentService;
    @Operation(summary = "分页查询预约信息")
    @GetMapping("page")
    public Result<IPage<AppointmentVo>> page(@RequestParam long current, @RequestParam long size, AppointmentQueryVo queryVo) {
        IPage<AppointmentVo> page = new Page<>(current,size);
        IPage<AppointmentVo> list = viewAppointmentService.findByPage(page,queryVo);
        return Result.ok(list);
    }

    @Operation(summary = "根据id更新预约状态")
    @PostMapping("updateStatusById")
    public Result updateStatusById(@RequestParam Long id, @RequestParam AppointmentStatus status) {
        LambdaUpdateWrapper<ViewAppointment> appointmentVoLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        //判断是否更新为待看房
        if(userCreditService.getById(id).getBreachCount()>=3&&status==AppointmentStatus.WAITING){
            //判断用户信用，爽约次数大于等于3则不允许该用户预约看房
            return Result.fail("爽约次数过多，不允许预约看房",400);
        }
        appointmentVoLambdaUpdateWrapper.eq(ViewAppointment::getId,id);
        appointmentVoLambdaUpdateWrapper.set(ViewAppointment::getAppointmentStatus,status);
        viewAppointmentService.update(appointmentVoLambdaUpdateWrapper);
        return Result.ok();
    }
    @XxlJob("appointmentJobHandler")
    public void appointmentJobHandler() throws Exception {
        List<ViewAppointment> expiredAppointments = viewAppointmentService.list(
                new LambdaQueryWrapper<ViewAppointment>()
                        .eq(ViewAppointment::getAppointmentStatus, AppointmentStatus.WAITING)
                        .lt(ViewAppointment::getAppointmentTime, LocalDateTime.now())
        );

        if (CollectionUtils.isEmpty(expiredAppointments)) return;

        // 更新预约状态
        for (ViewAppointment appointment : expiredAppointments) {
            appointment.setAppointmentStatus(AppointmentStatus.FAIL);
        }
        viewAppointmentService.updateBatchById(expiredAppointments);

        // 更新用户信用
        for (ViewAppointment appointment : expiredAppointments) {
            Long userId = appointment.getUserId();
            userCreditService.update(
                    new LambdaUpdateWrapper<UserCredit>()
                            .eq(UserCredit::getUserId, userId)
                            .setSql("credit_score = credit_score - 10")
                            .setSql("breach_count = breach_count + 1")
            );
        }
    }

}
